//数据库执行语句函数
const { sqlPromise } = require("../db/sqlPromise");
const { tree} = require("../common/common");
// 获取角色列表
exports.roles = async (ctx) => {
  let roleRes = await sqlPromise("select * from sp_role");
  let rightRes = await sqlPromise("select * from sp_permission");
  let data = roleRes.reduce((preVal, curVal, index) => {
    let {
      role_id: id,
      role_name: roleName,
      role_desc: roleDesc,
      ps_ids: pid,
    } = curVal;
    preVal[index] = { id, roleName, roleDesc, pid, children: [] };
    return preVal;
  }, []);
  let res = data.reduce((preVal, curVal, index) => {
    curVal.pid.split(",").map((item, inx) => {
      return rightRes.forEach((v, i) => {
        if (item == v.ps_id) {
          let {
            ps_id: id,
            ps_name: authName,
            ps_c: path,
            ps_pid: pid,
          } = rightRes[i];
          curVal.children[inx] = {
            id,
            authName,
            path: path == "" ? null : path,
            pid,
          };
        }
      });
    });
    curVal.children = tree(curVal.children);
    delete curVal.pid;
    preVal[index] = curVal;
    return preVal;
  }, []);
  ctx.body = {
    data: res,
    meta: {
      msg: "获取成功",
      status: 200,
    },
  };
};
//添加角色
exports.addRoles = async (ctx) => {
  let sql = "select * from sp_role where role_name=?";
  let results = await sqlPromise(sql, ctx.request.body.roleName);
  if (results.length > 0)
    return (ctx.body = {
      status: 404,
      msg: "创建失败 角色已存在",
    });
  let insertSql = "insert into sp_role set ?";
  let data = {
    role_name: ctx.request.body.roleName,
    role_desc: ctx.request.body.roleDesc,
  };
  await sqlPromise(insertSql, data);
  let dataSql = "select * from sp_role where role_name=?";
  let [dataRes] = await sqlPromise(dataSql, data.role_name);
  ctx.body = {
    data: {
      roleId: dataRes.role_id,
      roleName: dataRes.role_name,
      roleDesc: dataRes.role_desc,
    },
    meta: {
      msg: "角色创建成功",
      status: 200,
    },
  };
};
//根据id查询角色
exports.queryRole = async (ctx) => {
  await sqlPromise(`select * from sp_role where role_id=${ctx.params.id}`).then(
    (res) => {
      if (res.length) {
        ctx.body = {
          data: {
            roleId: res[0].role_id,
            roleName: res[0].role_name,
            roleDesc: res[0].role_desc,
          },
          meta: {
            msg: "查询成功",
            status: 200,
          },
        };
      } else {
        ctx.body = {
          msg: "该用户不存在",
          status: 404,
        };
      }
    }
  );
};
//编辑提交角色
exports.updateRole = async (ctx) => {
  let sql = "update sp_role set role_name=?,role_desc=? where role_id=?";
  await sqlPromise(sql, [
    ctx.query.roleName,
    ctx.query.roleDesc,
    ctx.params.id,
  ]).then(async (res) => {
    if (res.affectedRows != 1) {
      ctx.body = {
        msg: "编辑用户失败",
        status: 404,
      };
    } else {
      await sqlPromise(
        `select * from sp_role where role_id=${ctx.params.id}`
      ).then((res) => {
        ctx.body = {
          data: {
            roleId: res[0].role_id,
            roleName: res[0].role_name,
            roleDesc: res[0].role_desc,
          },
          meta: {
            msg: "更新成功",
            status: 200,
          },
        };
      });
    }
  });
};
//删除角色
exports.deleteRole = async (ctx) => {
  let sql = "delete from sp_role where role_id=?";
  await sqlPromise(sql, ctx.params.id).then((res) => {
    if (res.affectedRows != 1) {
      ctx.body = {
        msg: "删除角色失败",
        status: 404,
      };
    } else {
      ctx.body = {
        data: null,
        meta: {
          msg: "删除成功",
          status: 200,
        },
      };
    }
  });
};
//角色授权
exports.authorize = async (ctx) => {
  let results = await sqlPromise(
    "select a.ps_id,a.ps_name,a.ps_level,a.ps_pid,b.ps_api_path from sp_permission a join sp_permission_api b on a.ps_id=b.ps_id"
  );
  let data = results.reduce((preVal, curVal, index) => {
    let {
      ps_id: id,
      ps_name: authName,
      ps_level: level,
      ps_pid: pid,
      ps_api_path: path,
    } = curVal;
    preVal[index] = {
      id,
      authName,
      level,
      pid,
      path: path == "" ? null : path,
    };
    return preVal;
  }, []);
  let res = getData(tree(data),101)
  let sql = "select * from sp_role where role_id=?";
  await sqlPromise(sql, ctx.params.roleId).then((res) => {
    if(!res.length) return ctx.body={
      msg:'该角色不存在',
      status:404
  }
  });
  
  function getData(treeData,id){
    var checkId = [];
    var j = 0;
        for (var i in treeData) {
            if (treeData[i].id == id) {
                checkId[j++] = treeData[i];
            }
            if (treeData[i].children) {
                getData(treeData[i].children);
            } else {
                continue;
            }
        }
        return checkId;
  }
  
};
